import React, { useState, useEffect } from 'react';
import './index.css';
import { Button, Spin } from 'antd';

// 登陆
const Login = () => {
  const [token, setToken] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isShow, setIsShow] = useState(false); // 登陆后利用此标志刷新用户信息

  useEffect(() => {}, [isShow]);

  // 验证token
  const doLogin = async () => {
    setIsLoading(true);

    const response = await fetch(`https://cnodejs.org/api/v1/accesstoken`, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        accesstoken: token,
      }),
    });
    const result: ILoginInfo = await response.json();

    setIsLoading(false);

    if (result.success) {
      localStorage.setItem('loginname', result.loginname);
      localStorage.setItem('id', result.id);
      localStorage.setItem('avatar_url', result.avatar_url);
      setIsShow(true);
    }
  };

  // 获取已登陆用户的信息
  const getLoginInfo = () => {
    const id = localStorage.getItem('id') || '';
    const loginname = localStorage.getItem('loginname') || '';
    const avatar_url = localStorage.getItem('avatar_url') || '';

    return { id, loginname, avatar_url };
  };

  return (
    <div className="login">
      {isLoading ? (
        <Spin />
      ) : getLoginInfo().id !== '' ? (
        <div id={getLoginInfo().id}>
          <img src={getLoginInfo().avatar_url} alt={getLoginInfo().loginname} />
          <p>{getLoginInfo().loginname}</p>
        </div>
      ) : (
        <>
          <label htmlFor="token">输入accesstoken登陆</label>
          <input
            type="text"
            id="token"
            onChange={(e) => setToken(e.target.value)}
            value={token}
          />
          <Button type="primary" onClick={doLogin}>
            登陆
          </Button>
        </>
      )}
    </div>
  );
};

export default Login;
